// deluaxxtea.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <malloc.h>
#include <errno.h>
#include <string.h>
#include "xxtea.h"

int _tmain(int argc, _TCHAR* argv[])
{
	if (argc < 4)
	{
		printf("Invalid arguments.\nUsage: deluaxxtea SIGN KEY LUAC_FILE_PATH\n\n");
		return 255;
	}

	const char * sign = argv[1];
	const char * key = argv[2];
	const char  * luacPath = argv[3];
	int signLen = strlen(sign);
	int keyLen = strlen(key);
	if (keyLen == 0 || signLen == 0)
	{
		printf("Invalid sign or key.\n");
		return 255;
	}

	FILE * f = fopen(luacPath, "rb");
	if (f == NULL)
	{
		printf("Cannot open file: %d\n", errno);
		return 1;
	}

	struct stat fst = { 0 };
	int r = fstat(fileno(f), &fst);
	if (r != 0)
	{
		fclose(f);
		printf("Cannot get file size: %d\n", errno);
		return 2;
	}

	int flen = fst.st_size;
	char * buff = new char[flen];
	if (fread(buff, sizeof(unsigned char), flen, f) < flen)
	{
		delete [] buff;
		fclose(f);
		printf("Read file failed: %d\n", errno);
		return 3;
	}

	fclose(f);

	if (memcmp(buff, sign, signLen) != 0)
	{
		delete [] buff;
		printf("Signature not match for file.\n");
		return 4;
	}

	unsigned dataLen = 0;
	unsigned char key2[128] = { 0 };
	memcpy(key2, key, keyLen);
	unsigned char * text = xxtea_decrypt((unsigned char *)(buff + signLen), flen - signLen, key2, keyLen, &dataLen);

	printf("%s\n", (const char *)text);
	free(text);
	delete [] buff;

	return 0;
}

